"use strict";
import axios from "axios";
import api from "@/api/index";
import { Dialog,Toast} from 'vant';
let config = {
  baseURL: api.ASSET_SERVER_URL,
  timeout: 600 * 1000,
  withCredentials: true,  //本地开发用
};

const _axios = axios.create(config);

// 请求拦截器
_axios.interceptors.request.use(
  config => {
     return config;
  },
  error => {
    return Promise.reject(error);
  }
);


// 响应拦截器
_axios.interceptors.response.use(
  response=>{
    if(response.data.code == -1){
      Dialog.alert({
        title: '提示',
        message: '您还未登陆是否千万登陆？',
      }).then(() => {});
    }
    return response;
  },
  error=>{
    return Promise.reject(error);
  }
);

const mergeRequestData=(data)=>{
  let user_id=localStorage.getItem('YF_USER_INFOS_ID');
  user_id=user_id && user_id!='null' && user_id!='undefined'?user_id:false;
  let openid=localStorage.getItem('YF_USER_INFOS_OPENID');
  openid=openid && openid!='null' && openid!='undefined'?openid:false;
  if(user_id)data.user_id=user_id;
  if(openid)data.openid=openid;
  return data;
}

const request = {
  async get(url, data={}, config={}) {
    let requerData=mergeRequestData(data)
    if (config) {
      config.params = requerData;
      try {
        let res = await _axios.get(url, config);
        res = res.data;
        return new Promise(resolve => {
          resolve(res);
        });
      } catch (err) {
        Toast.fail('网络错误!');
      }
    } else {
      try {
        let res = await _axios.get(url, { params: requerData });
        res = res.data;
        return new Promise(resolve => {
          resolve(res);
        });
      } catch (err) {
        Toast.fail('网络错误!');
      }
    }
  },
  async post(url, data={}, config={}) {
    let requerData=mergeRequestData(data)
    try {
      let res = await _axios.post(url, requerData, config);
      res = res.data;
      return new Promise(resolve => {
        resolve(res);
      });
    } catch (err) {
      Toast.fail('网络错误!');
    }
  },
  downExcel(url,params,filname){
    return new Promise((resolve,reject) => {
      axios({
        method: "GET",
        url: api.AssetServerUrl+url,
        params: params,
        headers:{
            token:sessionStorage.getItem("token")
        },
        responseType: "blob"
    })
        .then(res => {
            //console.log(res);return false;
            const blob = new Blob([res.data], {
                type: "application/vnd.ms-excel;charset=utf-8"
            });
            const downloadElement = document.createElement("a");
            const href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = filname+'.xls'; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放掉blob对象
            resolve(res);
        })
        .catch(err => {
          reject(err)
        });
    });
  },
  downMetod(url,fileName){
    axios.post(url, {}, {
      responseType: 'blob'
    }).then(function(res){
      var blob = res.data;
     // FileReader主要用于将文件内容读入内存
      var reader = new FileReader();
      reader.readAsDataURL(blob);
      // onload当读取操作成功完成时调用
      reader.onload = function(e) {
        var a = document.createElement('a');
        a.download = fileName;
        a.href = e.target.result;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
    });
  }
};
export default request;
